package com.kfm.common.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

public class QRCodeUtil {
    /**
     * 生成二维码图片
     *
     * @param data     待编码成二维码的数据
     * @param filePath 保存二维码图片的文件路径
     * @param fileName 保存二维码图片的文件名
     */
    public static void generateQRCode(String data, String filePath, String fileName) {
        int width = 300;
        int height = 300;

        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        try {
            // 将字符串生成二维码矩阵
            BitMatrix matrix = new MultiFormatWriter().encode(data, BarcodeFormat.QR_CODE, width, height, hints);

            // 将二维码矩阵保存为图片文件
            Path path = FileSystems.getDefault().getPath(filePath, fileName);
            MatrixToImageWriter.writeToPath(matrix, "PNG", path);
        } catch (WriterException | IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成带有二维码的图片，并将图片写入输出流
     * @param data 生成二维码的数据
     * @param outputStream 输出流对象，用于保存生成的图片
     */
    public static void generateQRCode(String data, OutputStream outputStream) {
        int width = 300;
        int height = 300;

        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        try {
            // 通过MultiFormatWriter将数据编码成二维码的位矩阵
            BitMatrix matrix = new MultiFormatWriter().encode(data, BarcodeFormat.QR_CODE, width, height, hints);

            // 将位矩阵转换为BufferedImage图片
            BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(matrix, new MatrixToImageConfig());

            // 将结果写入输出流
            MatrixToImageWriter.writeToStream(matrix, "PNG", outputStream);
        } catch (WriterException | IOException e) {
            e.printStackTrace();
        }
    }
}
